import re
import io
# now fitz is pymupdf
# pymupdf is a fork of PyMuPDF, which is the new name for the
import pymupdf as fitz
from PIL import Image


def page_to_image(page, dpi=300) -> Image:
    """将 PDF 页面转为 PIL.Image（优化分辨率）"""
    # 计算缩放比例（dpi -> zoom）
    zoom = dpi / 72  # MuPDF 默认 72 DPI
    matrix = fitz.Matrix(zoom, zoom)

    # 渲染页面为像素图（Pixmap）
    pix = page.get_pixmap(matrix=matrix, alpha=False)
    img_data = pix.tobytes("ppm")
    return Image.open(io.BytesIO(img_data))


def get_info_from_rect(page, rect, pattern, method="search"):
    text = page.get_text("text", clip=rect)
    print(text)
    match method:
        case "search":
            match = re.search(pattern, text)
            if match:
                return match.group(1)
        case "findall":
            match = re.findall(pattern, text)
            if match:
                return match
        case _:
            raise ValueError(f"Can't find {pattern} in the rect")
